<?php

class Admin_CargoController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
    	$form = new SON_Forms_Busca();
    	$cargo = new Cargo();
    	$session = new Zend_Session_Namespace('cargo');
    	 
    	$conditions = array();
    	if ($this->_request->isPost()) {
    		$session->post = $this->_request->getPost();
    	}
    	 
    	if ($session->post) {
    		$form->populate($session->post);
    		if ($session->post['filtro_busca']) {
    			$conditions = array('descricao LIKE ?' => '%' . $session->post['filtro_busca'] . '%');
    		}
    	}
    
    	$this->view->messages = $this->_helper->getHelper('FlashMessenger')->getMessages();
    	$this->view->form = $form;
    	$this->view->cargos = $cargo->search(
    		array(
    			'page' => $this->_getParam('page', 1),
    			'conditions' => $conditions
    		)
    	);
    }
    
    public function addAction()
    {
    	$form = new SON_Forms_Cargo();
    
    	if ($this->_request->isPost()) {
    		$data = $this->_request->getPost();
    		if ($form->isValid($data)) {
    
    			$cargo = new Cargo($data);
    			$cargo->save();
    			
    			$this->_helper->FlashMessenger(
    				array('success' => 'Cargo cadastrado com sucesso')
    			);
    
    			$this->_redirect('admin/cargo/');
    		} else {
    			$form->populate($data);
    			$this->view->error = $form->getMessages();
    		}
    	}
    
    	$this->view->form = $form;
    }
    
    public function editAction()
    {
    	$cargo = new Cargo();
    	$rcargo = $cargo->getAsArray((int) $this->_getParam('id', 0));
    
    	$form = new SON_Forms_Cargo();
    	$form->setAsEditForm($rcargo);
    
    	if ($this->_request->isPost()) {
    		$data = $this->_request->getPost();
    		if ($form->isValid($data)) {
    			$cargo = new Cargo($data);
    			$cargo->save();
    			
    			$this->_helper->FlashMessenger(
    				array('success' => 'Cargo alterado com sucesso')
    			);
    			
    			$this->_redirect('admin/cargo/');
    		} else {
    			$form->populate($data);
    			$this->view->error = $form->getMessages();
    		}
    	}
    
    	$this->view->form = $form;
    }
    
    public function deleteAction()
    {
    	$cargo = new Cargo();
    	if ((int) $this->_getParam('id') > 0) {
    		$cargo->delete((int) $this->_getParam('id'));
    		
    		$this->_helper->FlashMessenger(
    			array('success' => 'Cargo excluído com sucesso')
    		);
    	}
    
    	$this->_helper->viewRenderer->setNoRender();
    	$this->_redirect("admin/cargo/");
    }


}

